﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using Netkk.Common.Models;

namespace Netkk.Library.ActionResults
{
    public class UserImageResult : DownloadResult
    {
        public User User { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            // verify properties 
            if (User == null)
            {
                throw new ArgumentNullException("User");
            }

            string basePath = context.HttpContext.Server.MapPath("~/App_Data/UserImages");
            string thumbPath = Path.Combine(basePath, "Thumbs");


            string fileName;
            DirectoryInfo dinfo = new DirectoryInfo(basePath);
            FileInfo[] files = dinfo.GetFiles(string.Format("{0}.*", User.Id));
            if (files.Length > 0)
            {
                fileName = files[0].Name;
            }
            else
            {
                return; // TODO: Handle No Image
            }

            string thumbName = string.Format("{0}_{1}_{2}.jpg", Width, Height, Path.GetFileNameWithoutExtension(fileName));

            string fullFilePath = Path.Combine(basePath, fileName);
            string fullThumbPath = Path.Combine(thumbPath, thumbName);

            if (!File.Exists(fullThumbPath) && (Width > 0 || Height > 0))
            {
                using (FileStream fs = File.OpenRead(fullFilePath))
                {
                    if (fs.Length > 0)
                    {
                        string ext = Path.GetExtension(fullFilePath).ToLower();
                        if (ext == ".gif" || ext == ".jpg" || ext == ".png" || ext == ".bmp")
                        {
                            Bitmap bitmap = new Bitmap(fs);
                            if (ext == ".gif")
                            {
                                Bitmap realBitmap = new Bitmap(bitmap.Width, bitmap.Height);
                                for (int x = 0; x < bitmap.Width; x++)
                                {
                                    for (int y = 0; y < bitmap.Height; y++)
                                    {
                                        realBitmap.SetPixel(x, y, bitmap.GetPixel(x, y));
                                    }
                                }
                                bitmap.Dispose();
                                bitmap = realBitmap;
                            }

                            bitmap = ImageHandling.ResizeOrCropImage(bitmap, Width, Height);

                            if (File.Exists(fullThumbPath))
                            {
                                File.Delete(fullThumbPath);
                            }

                            bitmap.Save(fullThumbPath, ImageFormat.Jpeg);
                            bitmap.Dispose();
                        }
                    }
                }
            }

            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader("Content-Disposition", string.Format("filename={0}", fileName));
            context.HttpContext.Response.ContentType = "image/jpeg";

            string resultPath = File.Exists(fullThumbPath) ? fullThumbPath : fullFilePath;

            using (FileStream fs = File.OpenRead(resultPath))
            {
                WriteToStream(fs, context.HttpContext.Response.OutputStream);
            }

            context.HttpContext.Response.End();
        }
    }
}
